package com.website.quartz.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.website.common.util.HttpUtil;
import com.website.mybatis.entity.CompanyInfo;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.ResourceUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

public class CrawlCompanyInfo extends QuartzJobBean {

    private Logger logger = LoggerFactory.getLogger(CrawlCompanyInfo.class);
    String url = "http://qyxy.baic.gov.cn/djgg/release/getMoreKindNoticeList.do"; //1433個企業
    String getNoticeUrl = "http://qyxy.baic.gov.cn/djgg/release/getNoticeByNoticeId.do";

    private static Map<String, String> type = new HashMap<>();

    static{
        type.put("1","企业注销");
        type.put("2","企业减资");
        type.put("3","吸收合并");
        type.put("4","新设合并");
        type.put("6","个体转企业");
        type.put("8","存续分立");
        type.put("9","解散分立");
        type.put("s","撤销公告");
        type.put("10","企业变更");
        type.put("11","企业注销");
        type.put("12","不适宜名称");
        type.put("a1","未提交");
        type.put("a2","待校核");
        type.put("a3","校核通过");
        type.put("a4","修改");
        type.put("a5","退回");
        type.put("a6","被举报");
    }
    @Override
    public void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        logger.info("--------------抓取公示企业信息任务开始--------------");
        String pagerows = jobExecutionContext.getMergedJobDataMap().getString("pagerows");
        if(StringUtils.isBlank(pagerows)){
            pagerows = "20";//默认20条
        }
        try {
            //SessionFactory f = SpringContextUtil.getBean(SessionFactory.class);
            //Session session = f.openSession();
            //session.setFlushMode(FlushMode.MANUAL);
            String data = "{\"data\":[{\"vtype\":\"pagination\",\"name\":\"pagerows\",\"data\":#pagerows#},{\"vtype\":\"pagination\",\"name\":\"page\",\"data\":1}]}";
            Map<String, String> map = new HashMap<>(2);
            map.put("postData", data.replace("#pagerows#", pagerows));
            String res = HttpUtil.post(url, map, "utf-8");
            JSONObject json = JSON.parseObject(res);
            JSONObject js = (JSONObject) json.getJSONArray("data").get(0);
            js = js.getJSONObject("data");
            JSONArray ja = js.getJSONArray("rows");
            for (Object jj: ja){
                JSONObject jsonObject = (JSONObject) jj;
                map.remove("postData");
                map.put("noticeId", jsonObject.getString("noticeId"));
                res = reTry(getNoticeUrl, map, 2);
                JSONObject temp = JSON.parseObject(res);
                temp = ((JSONObject)temp.getJSONArray("data").get(0)).getJSONObject("data");
                CompanyInfo com = temp.getJSONObject("notice").toJavaObject(CompanyInfo.class);
                if(StringUtils.isNotBlank(jsonObject.getString("cancelJsonStr"))){
                    String cancelJsonStr = jsonObject.getString("cancelJsonStr");
                    JSONObject cancelJsonStr0 = (JSONObject) JSON.parseArray(cancelJsonStr).get(0);
                    com.setMembers(cancelJsonStr0.getString("members"));
                }
                com.setNoticeType(type.get(com.getNoticeType()));
                com.setState(type.get("a"+com.getState()));
                //try {
                //    save(com, session);
                //} catch (ConstraintViolationException e) {
                //    logger.error("保存公示企业信息任务-异常{}", e.getMessage());
                //}
                Thread.sleep(1000);
            }

        //} catch (ConstraintViolationException e) {
        //    logger.error("抓取公示企业信息任务-异常", e);
        } catch (IOException e) {
            logger.error("抓取公示企业信息任务-异常", e);
        } catch (InterruptedException e) {
            logger.error("抓取公示企业信息任务-异常", e);
        } finally {
            logger.info("--------------抓取公示企业信息任务结束--------------");
        }
    }

    //public void save(CompanyInfo com, Session session){
    //    Transaction t = session.beginTransaction();
    //    try {
    //        session.save(com);
    //    } catch (Exception e) {
    //        t.rollback();
    //        throw e;
    //    }
    //    t.commit();
    //}
    private String reTry(String url, Map<String, String> map, int time) throws IOException {
        try {
            return HttpUtil.post(url, map, "utf-8");
        } catch (IOException e) {
            if(time > 0){
                return reTry(url, map, --time);
            }else{
                throw e;
            }
        }
    }
    public static void main(String[] args) throws JobExecutionException, IOException {
//        new CrawlCompanyInfo().execute(null);
        BufferedReader bfr = Files.newBufferedReader(ResourceUtils.getFile("classpath:data.data").toPath(), Charset.forName("utf-8"));
        String data = bfr.readLine();
        bfr.close();
        System.out.println(data.replace("#pagerows#", "1000"));
    }
}
